package service

import (
	__ "base_srv/basic/baseproto"
	"base_srv/basic/config"
	"base_srv/untils"
	"context"
	"log"
	"path/filepath"
	"strings"
)

type Server struct {
	__.UnimplementedBaseInfoServer
}

// OssUpload OSS 上传文件
func (s *Server) OssUpload(_ context.Context, req *__.OssUploadReq) (*__.OssUploadResp, error) {

	if req.ObjectName == "" {
		filename := filepath.Base(req.Url)
		req.ObjectName = filename
	}
	err := untils.OssUpload(req.ObjectName, req.Url)
	if err != nil {
		log.Printf("ossUpload err:%v", err)
		return nil, err
	}
	url := untils.GetOssUrl(config.ConAll.BucketName, req.ObjectName)

	// 上传成功后，删除原有应用的安装包和图片
	// 仅处理应用相关的文件（ObjectName以"app_"开头）
	if strings.HasPrefix(req.ObjectName, req.ObjectName) {
		err = untils.DeleteApplicationFiles(req.ObjectName)
		if err != nil {
			return nil, err
		}
	}

	return &__.OssUploadResp{
			Url: url,
		},
		nil
}

// OssUploadPart  oss分片上传
func (s *Server) OssUploadPart(_ context.Context, req *__.OssUploadPartReq) (*__.OssUploadPartResp, error) {
	if req.ObjectName == "" {
		filename := filepath.Base(req.Url)
		req.ObjectName = filename
	}
	err := untils.OssMultipartUpload(req.ObjectName, req.Url)
	if err != nil {
		return nil, err
	}
	if strings.HasPrefix(req.ObjectName, req.ObjectName) {
		err = untils.DeleteApplicationFiles(req.ObjectName)
		if err != nil {
			return nil, err
		}
	}
	url := untils.GetOssUrl(config.ConAll.BucketName, req.ObjectName)
	return &__.OssUploadPartResp{
		Url: url,
	}, nil
}
